package com.epam.employeebase.command;

import java.util.List;

import org.apache.log4j.Logger;

import com.epam.employeebase.controller.RequestContent;
import com.epam.employeebase.dao.IEmployeeDAO;
import com.epam.employeebase.dao.exception.DAOException;
import com.epam.employeebase.entity.Employee;
import com.epam.employeebase.tag.Page;
import com.epam.employeebase.tag.PagingSupportTag;
import com.epam.employeebase.util.ResourceManager;

public final class EmployeeListCommand implements Command{
	private static final Logger logger = Logger.getLogger(EmployeeListCommand.class);
	private static final String ENTRIES_PER_PAGE_ATTRIBUTE_NAME = "entriesPerPage";
	private static final String PAGE_NUMBER_PARAMETER_NAME = "page";
	private static final String DAO_ATTRIBUTE_NAME = "dao";
	private static final String EMPLOYEES_NUMBER_ATTRIBUTE_NAME = "employeesNumber";
	private static final String EMPLOYEE_LIST_ATTRIBUTE_NAME = "employees";
	private static final String EXECUTION_TIME_ATTRIBUTE_NAME = "executionTime";
	@Override
	public String execute(RequestContent requestContent) {
		IEmployeeDAO dao = (IEmployeeDAO)requestContent.getSessionAttribute(DAO_ATTRIBUTE_NAME);
		try {
			int pageNumber = Integer.parseInt(requestContent.getRequestParameter(PAGE_NUMBER_PARAMETER_NAME));
			int entriesPerPage = (int)requestContent.getSessionAttribute(ENTRIES_PER_PAGE_ATTRIBUTE_NAME);
			
			Page page = PagingSupportTag.getPage(pageNumber, entriesPerPage);
			long startExecution = System.currentTimeMillis();
			List<Employee> employees = dao.list(page.getFirstEntry(), page.getEntriesNumber());
			long endExecution = System.currentTimeMillis();
			long executionTime = endExecution - startExecution;
			long employeesNumber = dao.employeeCount();
			requestContent.setRequestAttribute(EMPLOYEES_NUMBER_ATTRIBUTE_NAME, employeesNumber);
			requestContent.setRequestAttribute(EMPLOYEE_LIST_ATTRIBUTE_NAME, employees);
			requestContent.setRequestAttribute(EXECUTION_TIME_ATTRIBUTE_NAME, executionTime);
		} catch (DAOException e) {
			logger.error("DAOException", e);
		}
		return ResourceManager.getProperty(ResourceManager.LIST_PAGE_PATH);
	}
}
